<?php
class Content extends Controller {
	function Content()
	{
		parent::Controller();
		
		// check privacy
		global $BBX;
		$this->load->model('Membership_model');
		if (!preg_match('/(xml|rss)/', $this->uri->uri_string()) && !$BBX['bricabox']->privacy)
		{
			// make sure someone is logged in and a member
			if (!$this->Membership_model->is_member($BBX['bricabox']->id))
			{
				header("Location: /private");
				exit();
			}
		}
	}
	
	function create()
	{
		global $BBX;
		
		$this->load->model('Content_model');
		
		$bricabox_id = $this->input->post("bricabox_id");
		$type_id 	 = $this->input->post("type_id");
		$params		 = $this->input->post("content");
		
		// does the content already exist?
		$dateless_params = $params;
		unset($dateless_params['data_datetime']);
		if ($existing_id = $this->Content_model->content_exists($bricabox_id, $dateless_params))
		{
			$this->flashy->save_flash('notice', "We found an existing entry that matched what you just entered, so here it is.");
			header("Location: /content/{$existing_id}/" . url_title($dateless_params['field1_value'])); // spoof it
			exit(); // ensure we don't proceed
		}
		
		$content = $this->Content_model->save_content($bricabox_id, $type_id, $params, true);
		if ($content)
		{
			// record the activity
			$this->load->model('Activity_model');
			$this->Activity_model->log_activity(array(
				'action' 		=> 'added',
				'activity_type' => 'create_content',
				'content_id'	=> $content->id,
				'object'		=> $content->field1_value,
				'bricabox_id'	=> $bricabox_id,
				'extra_data'	=> $this->Content_model->get_content_type($type_id)->name,
				'subject'		=> username($this->userland->current_user())
			));
			
			// engage if we're using a button style
			$this->load->library('engagement');
			$this->load->model('Content_model');

			$type 		= 'create_entry';
			$klass 		= $this->engagement->engagement_for($BBX['bricabox']);
			$callback	= 'on_'.$type;
			$value		= 3;
			$klass->$callback($BBX['bricabox'], $content, $this->userland->current_user(), $type, $value);
			
			
			
			$this->flashy->save_flash('notice', "Awesome! Here's your new entry.");
			header("Location: " . content_url($content));
		}
		else
		{
			// handle failure
			$this->flashy->save_flash('error', "There was a problem adding your new entry.");
			header("Location: /");
		}
	}
	
	function show()
	{
		global $BBX;
		
		$this->load->library('engagement');
		$this->load->model('Bricabox_model');
		$this->load->model('Block_model');
		$this->load->model('Content_model');
		$this->load->model('Membership_model');
		$this->load->model('Activity_model');
		$this->load->helper('typography');
		$this->load->helper('text');
		$this->load->helper('url');
		
		$content 		= $this->Content_model->load_content($this->uri->segment(2), $BBX['bricabox']->id);
		$avail_blocks 	= $this->db->query('select * from blocks where lives_on = ? or lives_on = ? order by name asc', array('content', 'both'));
		$edit_layout 	= ($this->Membership_model->is_owner($BBX['bricabox']->id) && strpos($this->uri->uri_string(), 'edit_layout') !== false) ? true : false;
		
		$data = array(
			'BBX'			=> $BBX,
			'bricabox' 		=> $BBX['bricabox'],
			'content'		=> $content,
			'page_title'	=> "{$content->field1_value} - {$BBX['bricabox']->name}",
			'blocks'		=> $this->Block_model->load_blocks_for_location('content', !$edit_layout, $content),
			'content_type'	=> $this->Content_model->get_content_type($content->content_type_id),
			'engage'		=> $this->engagement->engagement_for($BBX['bricabox']),
			'avail_blocks'	=> $avail_blocks,
			'activity'		=> $this->Activity_model->get_activity(array('content_id' => $content->id))
		);
		if (!$this->userland->logged_in() || (!$this->Membership_model->is_owner($BBX['bricabox']->id, $this->userland->current_user()->id)))
			$this->Bricabox_model->record_pageview($BBX['bricabox']->id);
			
		// rotate content flag
		$this->db->query('update bricaboxes set use_internal_ads = not use_internal_ads where id = ?', array($BBX['bricabox']->id));		
		
		$this->load->view('content/show', $data);
	}
	
	function edit()
	{
		global $BBX;
		
		$this->load->model('Bricabox_model');
		$this->load->model('Content_model');
		$this->load->model('Membership_model');
		
		$content = $this->Content_model->load_content($this->uri->segment(2), $BBX['bricabox']->id);
		
		$_ct = $this->Content_model->get_content_type($content->content_type_id);
		
		if (!$this->Content_model->user_can_edit($this->userland->current_user(), $content->user_id))
			show_404();
		
		$data = array(
			'BBX'			=> $BBX,
			'bricabox' 		=> $BBX['bricabox'],
			'content'		=> $content,
			'type_id'		=> $_ct->id,
			'bricabox_id'	=> $BBX['bricabox']->id,
			'is_only_type'	=> true,
			'is_edit'		=> true,
			'page_title'	=> "{$BBX['bricabox']->name}: {$content->field1_value} &gt; Edit",
			'content_type'	=> $_ct
		);
		$this->load->view('content/edit', $data);
	}
	
	function update()
	{
		global $BBX;
		
		$this->load->model('Content_model');
		
		$bricabox_id = $this->input->post("bricabox_id");
		$type_id 	 = $this->input->post("type_id");
		$params		 = $this->input->post("content");
		$content_id  = $this->input->post("content_id");
		$params['content_id'] = $content_id;
		
		$content = $this->Content_model->save_content($bricabox_id, $type_id, $params, false);
		if ($content)
		{
			$this->flashy->save_flash('notice', "Awesome! Your changes have been saved.");
		}
		else
		{
			// handle failure
			$this->flashy->save_flash('error', "Oops. We couldn't save your changes.");
		}
		header("Location: /content/{$content_id}");
	}
	
	function destroy()
	{
		global $BBX;
		
		$this->load->model('Content_model');
		
		$content_id = $this->uri->segment(2);
		$content 	= $this->Content_model->load_content($content_id, $BBX['bricabox']->id);
		
		if (!$this->Content_model->user_can_edit($this->userland->current_user(), $content->user_id))
			show_404();
		
		$this->Content_model->destroy_content($content_id);
		
		$this->flashy->save_flash('notice', 'Entry removed.');
		header("Location: /");
	}
	
	function list_content()
	{
		global $BBX;
		
		//$this->output->enable_profiler(true);
		
		$this->load->library('engagement');
		$this->load->model('Block_model');
		$this->load->model('Content_model');
		$this->load->model('Bricabox_model');
		$this->load->model('Membership_model');
		$this->load->model('Activity_model');
		$this->load->helper('inflector');
		$this->load->helper('string');
		$this->load->helper('text');
		$this->load->helper('typography');
		
		// parse the url for filter params
		$parts = $this->uri->uri_to_assoc(2); // consume everything after entries/
		
		// sorting
		$sortables = array(
			'title_az'  => 'contents.field1_value asc',
			'title_za'  => 'contents.field1_value desc',
			'date_desc' => 'contents.created_at desc',
			'date_asc'  => 'contents.created_at asc',
			'eng_desc'  => 'contents.cached_eng_count desc',
			'eng_asc'   => 'contents.cached_eng_count asc',
			'dt_asc' 	=> 'contents.data_datetime asc',
			'dt_desc' 	=> 'contents.data_datetime desc',
			'up'		=> 'contents.data_datetime asc' // special case
		);
		
		$upcoming = null;
		$order_by = null; // defaults to reverse chron
		if (isset($parts['sort']))
		{
			$order_by = $sortables[$parts['sort']];
			if ($parts['sort'] == 'up')
				$upcoming = true;
		}
		
		// content type
		$content_type_id = null;
		if (isset($parts['entry_type']) && $parts['entry_type'] != 'all')
		{
			$content_type_id = $this->Content_model->get_content_type_by_name($parts['entry_type'], $BBX['bricabox']->id)->id;
		}
		
		// limit (mainly for api use)
		$limit = null;
		if (isset($parts['limit']))
		{
			$limit = intval($parts['limit']);
		}
		
		// filter by category
		$_ctgy = isset($parts['categorized']) ? $parts['categorized'] : false;
		
		// filter by tags
		$_tags = isset($parts['tagged']) ? $parts['tagged'] : false;
		if ($_tags)
		{
			// CI converts spaces to _; change them back
			$_tags = str_replace('_', ' ', $_tags);
			$tags  = explode(':', $_tags);
		}
		else
			$tags = array();
		
		// search?
		$search = isset($parts['search']) ? url_safe_base64($parts['search'], 'decode') : false;
		
		// load content
		$content = $this->Content_model->load_all_filtered(
			$BBX['bricabox']->id, $order_by, $content_type_id, $limit, $_ctgy, $tags, $search, $upcoming
		);
		
		// load filterable blocks
		$blocks	 = $this->Block_model->load_blocks_for_list_view();
		
		// render the view
		$data = array(
			'BBX'			=> $BBX,
			'bricabox' 		=> $BBX['bricabox'],
			'content'		=> $content,
			'page_title'	=> "{$BBX['bricabox']->name}: Entries",
			'blocks'		=> $blocks,
			'sortables'		=> $sortables,
			'parts'			=> $parts,
			'content_types' => $this->Bricabox_model->get_content_types($BBX['bricabox']->id),
			'engage'		=> $this->engagement->engagement_for($BBX['bricabox']),
			'ctgys'			=> $this->Bricabox_model->get_categories($BBX['bricabox']->id),
			'activity'		=> $this->Activity_model->get_activity(array('bricabox_id' => $BBX['bricabox']->id))
		);
		
		// what kind of response is desired?
		if ($this->wants->xml() || @$parts['as'] == 'xml')
		{
			$this->output->set_header('Content-type: text/xml');
			$this->load->view('content/list_content_xml', $data);
		}
		else if($this->wants->rss() || @$parts['as'] == 'rss')
        {
			// check the private auth token (if passed) before output
			if (!$BBX['bricabox']->privacy)
			{
				if (!isset($parts['token']) || empty($parts['token']) || md5($BBX['bricabox']->id) != $parts['token'])
					show_404();
			}
            $this->output->set_header('Content-type: text/xml');
            $this->load->view('content/list_content_rss', $data);
		}
		else
			$this->load->view('content/list_content', $data);
	}
	
	function entry_tpl_fields()
	{
		global $BBX;
		
		$this->load->model('Content_model');
		
		$bricabox_id = $this->input->post('bricabox_id');
		$type_id	 = $this->input->post('type_id');
		
		$content_type = $this->Content_model->get_content_type($type_id);
		
		$data = array(
			'bricabox_id'	=> $bricabox_id,
			'type_id'		=> $type_id,
			'content_type'	=> $content_type,
			'is_only_type'	=> $this->input->post('only_type') == 'true' ? true : false
		);
		
		$this->load->view('content/entry_fields', $data);
	}
	
	function load_wiki_version()
	{
		$this->load->helper('typography');
		$this->load->helper('text');
		$this->load->helper('url');
		
		$ver_id = $this->uri->segment(4);
		$query  = $this->db->query('select * from wiki_versions where id = ?', array($ver_id));
		echo auto_typography(ascii_to_entities(auto_link($query->first_row()->value, 'both', true)));
	}
	
	function set_default_wiki_version()
	{
		$query = $this->db->query('select * from wiki_versions where id = ?', array($this->uri->segment(4)));
		$ver   = $query->first_row();
		$ver->user_id = $this->userland->current_user()->id;
		$ver->id 	  = null;
		$ver->created_at = mysql_now();
		$ver->updated_at = $ver->created_at;
		$this->db->insert('wiki_versions', $ver);
		echo 1;
	}
	
	function sitemap()
	{
		global $BBX;
		if (!isset($BBX['bricabox']))
		{
			show_404();
			exit();
		}
		
		/*
		$query = $this->db->query('select contents.id,contents.updated_at,bricaboxes.subdomain from contents
			inner join bricaboxes on bricaboxes.id = contents.bricabox_id
			order by contents.updated_at desc');
		*/
		$query = $this->db->query('select id,field1_value,updated_at,? as subdomain from contents
			where bricabox_id = ?
			order by updated_at desc', array($BBX['bricabox']->subdomain, $BBX['bricabox']->id));
		
		$this->output->set_header('Content-type: text/xml');
		$this->load->view('content/sitemap', array('content' => $query, 'bricabox' => $BBX['bricabox']));
	}
	
	function sitemap_index()
	{
		global $BBX;
		if (isset($BBX['bricabox']))
		{
			show_404();
			exit();
		}
		
		$query = $this->db->query('select subdomain from bricaboxes');
		
		$this->output->set_header('Content-type: text/xml');
		$this->load->view('content/sitemap_index', array('bricaboxes' => $query));
	}
	
	function flag_content()
	{
		$user_id = $this->userland->logged_in() ? $this->userland->current_user()->id : -1;
		$c_id    = $this->uri->segment(2);
		$b_id    = $this->input->post('bricabox_id');
		$ip      = $this->input->server('REMOTE_ADDR');
		$this->db->query("INSERT INTO content_flags VALUES(NULL,?,?,?,NOW(),?)",
			array($c_id, $b_id, $ip, $user_id));
	}
}
?>